import urllib.request
import urllib.parse
from bs4 import BeautifulSoup
import requests


# 获取网页数据  https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/index.html
def getDate():
    url = 'https://down.ali213.net/pcgame/'
    # 设置参数
    head = {"User-Agent": "Chrome/87.0.4280.88 Safari/537.36"}
    # 转换为字符
    head_b = bytes(urllib.parse.urlencode(head), encoding='utf-8')

    # 创建reuest 对象
    req = urllib.request.Request(url, method='GET')

    # 打开链接
    html = urllib.request.urlopen(req)

    # 格式换返回页面
    html = html.read().decode('utf-8')
    return html


# 获取网页特定数据
def getGamePic():
    html = getDate()
    soup = BeautifulSoup(html, 'lxml')

    # 查询类
    cl = soup.find_all(class_='famous-li')
    i = 0
    for items in cl:
        print(items)
        i += 1
        src = items.find('img')
        game_name = items.find(class_='game-name')
        pic_src = None
        if i > 6:
            pic_src = src.get('data-original')
        else:
            pic_src = src.get('src')
        pic_src = 'http:' + pic_src
        print(pic_src)
        download(pic_src, game_name.string)


def download(pic_url, game_name):
    path = 'e://download'
    # urllib.request.urlretrieve(pic_url, path)
    game_path = 'e://download/' + game_name + '.jpg'
    pic = requests.get(pic_url)
    with open(game_path, 'wb') as f:
        f.write(pic.content)

getGamePic()
